/* Copyright (c) 2022 渝州大数据实验室
 *
 * Lanius is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *
 *     http://license.coscl.org.cn/MulanPSL2
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
/*
 * @description: http类的封装
 * @fileName: http.ts
 * @author: zoujunjie
 * @date: 2022-07-05
 */
import request from "./request";

interface IHttpParam {
  url: string;
  params?: { [key: string]: any };
  data?: any;
}

class BaseRequest {
  __baseUrl = "/api";

  constructor() {
    if (new.target === BaseRequest) {
      throw new Error("BaseRequest 类不能被实例化");
    }
  }

  getMethod() {
    throw new Error("当前方法必须被继承");
  }

  __query(params?: { [key: string]: any }) {
    if (params) {
      const _query_arr = [];
      for (let i in params) {
        _query_arr.push(i + "=" + params[i]);
      }
      return _query_arr.length ? "?" + _query_arr.join("&") : "";
    }
    return "";
  }

  _call(httpParam: IHttpParam) {
    return new Promise((resolve, reject) => {
      request({
        url: this.__baseUrl + httpParam.url + this.__query(httpParam.params),
        data: httpParam.data,
        method: this.getMethod(),
      } as any)
        .then((response) => {
          resolve(response);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }
}

class putRequest extends BaseRequest {
  getMethod() {
    return "PUT";
  }
}

class getRequest extends BaseRequest {
  getMethod() {
    return "GET";
  }
}

class postRequest extends BaseRequest {
  getMethod() {
    return "POST";
  }
}

class deleteRequest extends BaseRequest {
  getMethod() {
    return "DELETE";
  }
}

class HttpClient {
  private _postRequest;
  private _putRequest;
  private _getRequest;
  private _deleteRequest;
  constructor() {
    this._postRequest = new postRequest();
    this._putRequest = new putRequest();
    this._getRequest = new getRequest();
    this._deleteRequest = new deleteRequest();
  }

  post = (httpParam: IHttpParam) => {
    return this._postRequest._call(httpParam);
  };
  put = (httpParam: IHttpParam) => {
    return this._putRequest._call(httpParam);
  };
  get = (httpParam: IHttpParam) => {
    return this._getRequest._call(httpParam);
  };
  delete = (httpParam: IHttpParam) => {
    return this._deleteRequest._call(httpParam);
  };
}

// const $http = {
//     post:(httpParam) => {
//         return new postRequest()._call(httpParam)
//     },
//     put:(httpParam) => {
//         return new putRequest()._call(httpParam)
//     },
//     get:(httpParam)=>{
//         return new getRequest()._call(httpParam)
//     }
// }
export { HttpClient };
